package so.sao.shop.supplier.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class BeanUtils extends org.springframework.beans.BeanUtils {

	public static Map<String,Object> copyObjectToMap(Object target,Class<?> clazz) {
		return copyObjectToMap(target,clazz,null);
	}

	/**
	 * copy对象的字段到map
	 * @param target		目标对象
	 * @param clazz			map的实现
	 * @param ignoreNull	是否忽略null值,默认忽略null值
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,Object> copyObjectToMap(Object target,Class<?> clazz,Boolean ignoreNull) {
		if (ignoreNull == null) {
			ignoreNull = true;
		}
		Map<String,Object> map = null;
		try {
			map = (Map<String, Object>) clazz.newInstance();
			Method[] methods = target.getClass().getDeclaredMethods();
			for(Method method:methods) {
				if(method.getName().contains("set")) {
					continue ;
				}
				Annotation[] annotations = method.getAnnotations();
				Object value = method.invoke(target);
				if( (ignoreNull && value == null) || ignore(annotations)) {
					continue ;
				}
				String column = method.getName().replace("get", "");
				char first = column.charAt(0);
				column = column.substring(1);
				column = String.valueOf(first).toLowerCase() + column;
				map.put(column, value);
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		return map;
	}
	
	private static Boolean ignore(Annotation[] annotations) {
		for(Annotation annotation:annotations) {
			if(annotation.annotationType().equals(JsonIgnore.class)) {
				return true;
			}
		}
		return false;
	}

}
